<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width,initial-scale=1"><title>JavaWeb🌍文件上传和下载 | 小李博客</title><meta name="keywords" content="JavaWeb"><meta name="author" content="小李博客"><meta name="copyright" content="小李博客"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="文件上传文件上传概述 实现web开发中的文件上传功能，需完成如下二步操作： 在web页面中添加上传输入项 在servlet中读取上传文件的数据，并保存到本地硬盘中   如何在web页面中添加上传输入项?&lt;input type&#x3D;&quot;file&quot;&gt;标签用于在web页面中添加文件上传输入项，设置文件上传输入项时须注意： 必须要设置input输入项的name属性，否则浏览器将不">
<meta property="og:type" content="article">
<meta property="og:title" content="JavaWeb🌍文件上传和下载">
<meta property="og:url" content="http://xiaoliblog.cn/page/JavaWeb12.html">
<meta property="og:site_name" content="小李博客">
<meta property="og:description" content="文件上传文件上传概述 实现web开发中的文件上传功能，需完成如下二步操作： 在web页面中添加上传输入项 在servlet中读取上传文件的数据，并保存到本地硬盘中   如何在web页面中添加上传输入项?&lt;input type&#x3D;&quot;file&quot;&gt;标签用于在web页面中添加文件上传输入项，设置文件上传输入项时须注意： 必须要设置input输入项的name属性，否则浏览器将不">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://cdn.jsdelivr.net/gh/xiaoliblog/image@41021477288a29257324f7413b81c299b3dec54e/2021/03/21/3d05e9b134d98fc70cebf887c1359f71.png">
<meta property="article:published_time" content="2021-01-15T03:25:28.395Z">
<meta property="article:modified_time" content="2021-03-27T14:37:37.626Z">
<meta property="article:author" content="小李博客">
<meta property="article:tag" content="JavaWeb">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://cdn.jsdelivr.net/gh/xiaoliblog/image@41021477288a29257324f7413b81c299b3dec54e/2021/03/21/3d05e9b134d98fc70cebf887c1359f71.png"><link rel="shortcut icon" href="https://cdn.jsdelivr.net/gh/xiaoliblog/image@6b5e7ef72be1c8973d94e5a9c49accbf775ad820/2021/02/01/c485da031fe0e464d04eaba8a66c4a8f.png"><link rel="canonical" href="http://xiaoliblog.cn/page/JavaWeb12"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/node-snackbar/dist/snackbar.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/instantsearch.js@2.10.5/dist/instantsearch.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/instantsearch.js@2.10.5/dist/instantsearch.min.js" defer></script><script>const GLOBAL_CONFIG = { 
  root: '/',
  algolia: {"appId":"RTG4CPNBLJ","apiKey":"f1745bdad68ceec57653b78244fe332c","indexName":"MyBlogIndex","hits":{"per_page":6},"languages":{"input_placeholder":"搜索文章","hits_empty":"找不到您查询的内容：${query}","hits_stats":"找到 ${hits} 条结果，用时 ${time} 毫秒"}},
  localSearch: undefined,
  translate: {"defaultEncoding":2,"translateDelay":0,"msgToTraditionalChinese":"繁","msgToSimplifiedChinese":"簡"},
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":200},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '天',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: {"limitCount":100,"languages":{"author":"作者: 小李博客","link":"链接: ","source":"来源: 小李博客","info":"著作权归作者所有。商业转载请联系作者获得授权，非商业转载请注明出处。"}},
  lightbox: 'mediumZoom',
  Snackbar: {"chs_to_cht":"你已切换为繁体","cht_to_chs":"你已切换为简体","day_to_night":"你已切换为深色模式","night_to_day":"你已切换为浅色模式","bgLight":"#49b1f5","bgDark":"#121212","position":"top-center"},
  source: {
    jQuery: 'https://cdn.jsdelivr.net/npm/jquery@latest/dist/jquery.min.js',
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/js/jquery.justifiedGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/css/justifiedGallery.min.css'
    },
    fancybox: {
      js: 'https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.js',
      css: 'https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: false,
  isanchor: true
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = { 
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2021-03-27 22:37:37'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const fontSizeVal = saveToLocal.get('global-font-size')
    if (fontSizeVal !== undefined) {
      document.documentElement.style.setProperty('--global-font-size', fontSizeVal + 'px')
    }
    })(window)</script><link rel="stylesheet" href="/css/MyStyle/MyStyle.css" media="defer" onload="this.media='all'"/><link rel="stylesheet" href="/css/MyStyle/tagStyle.css" media="defer" onload="this.media='all'"/><link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/zykjofficial/zykjresource@master/css/font-awesome-animation.min.css" media="defer" onload="this.media='all'"/><link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/sviptzk/StaticFile_HEXO@latest/butterfly/css/font-awesome-animation.min.css" media="defer" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/sviptzk/StaticFile_HEXO@latest/butterfly/css/plugins.min.css" media="defer" onload="this.media='all'"><meta name="generator" content="Hexo 5.2.0"><link rel="alternate" href="/atom.xml" title="小李博客" type="application/atom+xml">
</head><body><div id="web_bg"></div><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="author-avatar"><img class="avatar-img" src="https://cdn.jsdelivr.net/gh/xiaoliblog/image@6b5e7ef72be1c8973d94e5a9c49accbf775ad820/2021/02/01/c485da031fe0e464d04eaba8a66c4a8f.png" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="site-data"><div class="data-item is-center"><div class="data-item-link"><a href="/archives/"><div class="headline">文章</div><div class="length-num">210</div></a></div></div><div class="data-item is-center"><div class="data-item-link"><a href="/tags/"><div class="headline">标签</div><div class="length-num">38</div></a></div></div><div class="data-item is-center"><div class="data-item-link"><a href="/categories/"><div class="headline">分类</div><div class="length-num">56</div></a></div></div></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 主页</span></a></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/box/"><i class="fa-fw fa fa-briefcase"></i><span> 工具箱</span></a></div><div class="menus_item"><a class="site-page" href="javascript:void(0);"><i class="fa-fw fas fa-book"></i><span> 找文章</span><i class="fas fa-chevron-down expand"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></li><li><a class="site-page child" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></li><li><a class="site-page child" href="/categories/"><i class="fa-fw fa fa-folder-open"></i><span> 分类</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fa fa-address-card"></i><span> 关于</span></a></div><div class="menus_item"><a class="site-page" href="/messageboard/"><i class="fa-fw fa fa-paper-plane"></i><span> 留言</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="not-top-img" id="page-header"><nav id="nav"><span id="blog_name"><a id="site-name" href="/">小李博客</a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search"><i class="fas fa-search fa-fw"></i><span> 搜索</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 主页</span></a></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/box/"><i class="fa-fw fa fa-briefcase"></i><span> 工具箱</span></a></div><div class="menus_item"><a class="site-page" href="javascript:void(0);"><i class="fa-fw fas fa-book"></i><span> 找文章</span><i class="fas fa-chevron-down expand"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></li><li><a class="site-page child" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></li><li><a class="site-page child" href="/categories/"><i class="fa-fw fa fa-folder-open"></i><span> 分类</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fa fa-address-card"></i><span> 关于</span></a></div><div class="menus_item"><a class="site-page" href="/messageboard/"><i class="fa-fw fa fa-paper-plane"></i><span> 留言</span></a></div></div><div id="toggle-menu"><a class="site-page"><i class="fas fa-bars fa-fw"></i></a></div></div></nav></header><main class="layout" id="content-inner"><div id="post"><div id="post-info"><h1 class="post-title">JavaWeb🌍文件上传和下载</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2021-01-15T03:25:28.395Z" title="发表于 2021-01-15 11:25:28">2021-01-15</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2021-03-27T14:37:37.626Z" title="更新于 2021-03-27 22:37:37">2021-03-27</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/Web%E5%89%8D%E7%AB%AF/">Web前端</a><i class="fas fa-angle-right post-meta-separator"></i><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/Web%E5%89%8D%E7%AB%AF/JavaWeb/">JavaWeb</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-wordcount"><i class="far fa-file-word fa-fw post-meta-icon"></i><span class="post-meta-label">字数总计:</span><span class="word-count">4.3k</span><span class="post-meta-separator">|</span><i class="far fa-clock fa-fw post-meta-icon"></i><span class="post-meta-label">阅读时长:</span><span>17分钟</span></span><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="JavaWeb🌍文件上传和下载"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"></span></span></div></div></div><article class="post-content" id="article-container"><h1 id="文件上传"><a href="#文件上传" class="headerlink" title="文件上传"></a>文件上传</h1><h2 id="文件上传概述"><a href="#文件上传概述" class="headerlink" title="文件上传概述"></a>文件上传概述</h2><ul>
<li>实现web开发中的文件上传功能，需完成如下二步操作：<ol>
<li>在web页面中添加上传输入项</li>
<li>在servlet中读取上传文件的数据，并保存到本地硬盘中</li>
</ol>
</li>
<li>如何在web页面中添加上传输入项?<code>&lt;input type=&quot;file&quot;&gt;</code>标签用于在web页面中添加文件上传输入项，设置文件上传输入项时须注意：<ul>
<li>必须要设置input输入项的name属性，否则浏览器将不会发送上传文件的数据；</li>
<li>必须把form的enctype属值设为<code>multipart/form-data</code>，设置该值后，浏览器在上传文件时，将把文件数据附带在http请求消息体中，并使用ＭＩＭＥ协议对上传的文件进行描述，以方便接收方对上传数据进行解析和处理。</li>
</ul>
</li>
<li>如何在Servlet中读取文件上传数据，并保存到本地硬盘中?<ul>
<li>Request对象提供了一个<code>getInputStream</code>方法，通过这个方法可以读取到客户端提交过来的数据。但由于用户可能会同时上传多个文件，在servlet端编程直接读取上传数据，并分别解析出相应的文件数据是一项非常麻烦的工作；</li>
<li>为方便用户处理文件上传数据，Apache 开源组织提供了一个用来处理表单文件上传的一个开源组件（ Commons-fileupload ），该组件性能优异，并且其API使用极其简单，可以让开发人员轻松实现web文件上传功能，因此在web开发中实现文件上传功能，通常使用<code>Commons-fileupload组件实现</code></li>
</ul>
</li>
<li>使用Commons-fileupload组件实现文件上传，需要导入该组件相应的支撑jar包：<code>Commons-fileupload</code>和<code>commons-io</code>。commons-io 不属于文件上传组件的开发jar文件，但Commons-fileupload 组件从1.1 版本开始，它工作时需要commons-io包的支持。</li>
</ul>
<h2 id="准备工作"><a href="#准备工作" class="headerlink" title="准备工作"></a>准备工作</h2><ul>
<li>对于文件上传，浏览器在上传的过程中是将文件以流的形式提交到服务器端的</li>
<li>一般采用Apache的开源工具<code>common-fileupload</code>这个文件上传组件</li>
<li><code>common-fileupload</code>是依赖于<code>common-io</code>这个包的，所以还需要下载这个包</li>
<li>Maven导入jar依赖</li>
</ul>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">&lt;!-- https://mvnrepository.com/artifact/commons-io/commons-io --&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>commons-io<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>commons-io<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">version</span>&gt;</span>2.6<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="comment">&lt;!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload --&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>commons-fileupload<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>commons-fileupload<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">version</span>&gt;</span>1.4<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br></pre></td></tr></table></figure>

<ul>
<li>其他依赖</li>
</ul>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">&lt;!--Servlet--&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">      <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>javax.servlet<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">      <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>javax.servlet-api<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">      <span class="tag">&lt;<span class="name">version</span>&gt;</span>4.0.1<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line">      <span class="tag">&lt;<span class="name">scope</span>&gt;</span>provided<span class="tag">&lt;/<span class="name">scope</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line"><span class="comment">&lt;!--JSP--&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">      <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>javax.servlet.jsp<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">      <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>javax.servlet.jsp-api<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">      <span class="tag">&lt;<span class="name">version</span>&gt;</span>2.2.1<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line">      <span class="tag">&lt;<span class="name">scope</span>&gt;</span>provided<span class="tag">&lt;/<span class="name">scope</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">      <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>javax.servlet.jsp.jstl<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">      <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>jstl<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">      <span class="tag">&lt;<span class="name">version</span>&gt;</span>1.2<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br></pre></td></tr></table></figure>

<ul>
<li>文件上传对页面的要求<ul>
<li>必须使用表单，而不能是超链接</li>
<li>表单的<strong>method</strong>必须是<code>POST</code>，而不能是GET，因为GET上传大小有限制</li>
<li>表单的<strong>enctype</strong>必须是<code>multipart/form-data</code></li>
<li>在表单中添加file表单字段，即<code>&lt;input type=&quot;file&quot; name=&quot;xxx&quot;/&gt;</code></li>
</ul>
</li>
</ul>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">form</span> <span class="attr">action</span>=<span class="string">&quot;$&#123;pageContext.request.contextPath &#125;/FileUploadServlet&quot;</span></span></span><br><span class="line"><span class="tag"><span class="attr">method</span>=<span class="string">&quot;post&quot;</span> <span class="attr">enctype</span>=<span class="string">&quot;multipart/form-data&quot;</span>&gt;</span></span><br><span class="line"> </span><br><span class="line">用户名：<span class="tag">&lt;<span class="name">input</span> <span class="attr">type</span>=<span class="string">&quot;text&quot;</span> <span class="attr">name</span>=<span class="string">&quot;username&quot;</span>/&gt;</span><span class="tag">&lt;<span class="name">br</span>/&gt;</span></span><br><span class="line">文件1：<span class="tag">&lt;<span class="name">input</span> <span class="attr">type</span>=<span class="string">&quot;file&quot;</span> <span class="attr">name</span>=<span class="string">&quot;file1&quot;</span>/&gt;</span><span class="tag">&lt;<span class="name">br</span>/&gt;</span></span><br><span class="line">文件2：<span class="tag">&lt;<span class="name">input</span> <span class="attr">type</span>=<span class="string">&quot;file&quot;</span> <span class="attr">name</span>=<span class="string">&quot;file2&quot;</span>/&gt;</span><span class="tag">&lt;<span class="name">br</span>/&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">input</span> <span class="attr">type</span>=<span class="string">&quot;submit&quot;</span> <span class="attr">value</span>=<span class="string">&quot;提交&quot;</span>/&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">form</span>&gt;</span></span><br></pre></td></tr></table></figure>

<h1 id="fileupload工作流程"><a href="#fileupload工作流程" class="headerlink" title="fileupload工作流程"></a>fileupload工作流程</h1><p><img src="https://cdn.jsdelivr.net/gh/xiaoliblog/image@5f5400e45db5a402e85ad8f5fbcde9e7d3d4a13c/2021/03/27/8b80c849a1ae22bce3f3f42a6b2c2823.png"></p>
<ul>
<li><code>ServletFileUpload</code>负责处理上传的文件数据，并将表单中的每个输入项封装成一个<code>FileItem</code>对象，在使用<code>ServletFileUpload</code>对象解析请求时需要<code>DiskFileItemFactory</code>对象</li>
<li>所以，我们需要在进行解析工作前构造好<code>DiskFileItemFactory</code>对象，通过<code>ServletFileItem</code>对象的构造方法或<code>setFileItemFactory()</code>设置<code>ServletFileUpload</code>对象的<code>fileItemFactory</code>属性</li>
</ul>
<h1 id="fileupload核心API"><a href="#fileupload核心API" class="headerlink" title="fileupload核心API"></a>fileupload核心API</h1><p><img src="https://cdn.jsdelivr.net/gh/xiaoliblog/image@5a4502dec0e6388a819b1fedcf2f9076883e6b49/2021/03/27/67e659d0e1f394f5cc964f4762bc5ff3.png"></p>
<h2 id="DiskFileItemFactory工厂类"><a href="#DiskFileItemFactory工厂类" class="headerlink" title="DiskFileItemFactory工厂类"></a>DiskFileItemFactory工厂类</h2><ul>
<li><code>DiskFileItemFactory</code> 是创建 FileItem 对象的工厂，这个工厂类常用方法：<ul>
<li><code>public DiskFileItemFactory(int sizeThreshold, java.io.File repository)</code><ul>
<li>构造方法；</li>
</ul>
</li>
<li><code>public void setSizeThreshold(int sizeThreshold)</code> <ul>
<li>设置内存缓冲区的大小，默认值为10K。当上传文件大于缓冲区大小时， fileupload组件将使用临时文件缓存上传文件。</li>
</ul>
</li>
<li><code>public void setRepository(java.io.File repository)</code> <ul>
<li>指定临时文件目录，默认值为当前用户的系统临时文件目录，可通过System.getProperty(“java.io.tmpdir”)打印查看；</li>
</ul>
</li>
</ul>
</li>
</ul>
<h2 id="ServletFileUpload解析器"><a href="#ServletFileUpload解析器" class="headerlink" title="ServletFileUpload解析器"></a>ServletFileUpload解析器</h2><ul>
<li><code>ServletFileUpload</code>负责处理上传的文件数据，并将表单中的每个输入项封装成一个<code>FileItem</code>对象中，使用其<code>parseRequest(HttpServletRequest)</code>方法可以将通过表单中每一个HTML标签提交的数据封装成一个<code>FileItem</code>对象，然后以<code>List</code>列表的形式返回。使用该方法处理上传文件简单易用</li>
<li>常用方法有：<ul>
<li><code>boolean isMultipartContent(HttpServletRequest request)</code> <ul>
<li>判断上传表单是否为multipart/form-data类型；</li>
</ul>
</li>
<li><code>List parseRequest(HttpServletRequest request)</code><ul>
<li>解析request对象，并把表单中的每一个输入项包装成一个fileItem 对象，并返回一个保存了所有FileItem的list集合；</li>
</ul>
</li>
<li><code>setFileSizeMax(long fileSizeMax)</code><ul>
<li>设置上传文件的最大值；</li>
</ul>
</li>
<li><code>setSizeMax(long sizeMax)</code><ul>
<li>设置上传文件总量的最大值；</li>
</ul>
</li>
<li><code>setHeaderEncoding(java.lang.String encoding)</code> <ul>
<li>设置编码格式；</li>
</ul>
</li>
</ul>
</li>
</ul>
<h2 id="FileItem表单字段域对象"><a href="#FileItem表单字段域对象" class="headerlink" title="FileItem表单字段域对象"></a>FileItem表单字段域对象</h2><table>
<thead>
<tr>
<th align="center">处理普通字段方法</th>
<th align="center">说明</th>
</tr>
</thead>
<tbody><tr>
<td align="center"><code>boolean isFormField()</code></td>
<td align="center">判断是否为普通字段</td>
</tr>
<tr>
<td align="center"><code>String getFieldName()</code></td>
<td align="center">返回表单字段（普通字段）名称</td>
</tr>
<tr>
<td align="center"><code>String getString()</code></td>
<td align="center">返回普通字段的值</td>
</tr>
<tr>
<td align="center"><code>String getString(String encoding)</code></td>
<td align="center">返回普通字段的值，并设置请求参数编码，常用于get提交</td>
</tr>
</tbody></table>
<table>
<thead>
<tr>
<th align="center">处理上传字段方法</th>
<th align="center">说明</th>
</tr>
</thead>
<tbody><tr>
<td align="center"><code>String getContentType()</code></td>
<td align="center">返回表单请求类型，即request请求头中的Content-type的内容，可用来限制文件上传的类型</td>
</tr>
<tr>
<td align="center"><code>String getName()</code></td>
<td align="center">返回文件名(全路径名：例如C:\a.txt)</td>
</tr>
<tr>
<td align="center"><code>InputStream getInputStream()</code></td>
<td align="center">返回表单输入流对象</td>
</tr>
<tr>
<td align="center"><code>void write(File file)</code></td>
<td align="center">将上传文件写入到磁盘</td>
</tr>
<tr>
<td align="center"><code>void delete()</code></td>
<td align="center">删除该上传字段存储在磁盘上的临时文件</td>
</tr>
</tbody></table>
<h1 id="文件上传案例"><a href="#文件上传案例" class="headerlink" title="文件上传案例"></a>文件上传案例</h1><h2 id="实现步骤"><a href="#实现步骤" class="headerlink" title="实现步骤"></a>实现步骤</h2><ul>
<li>判断上传的文件是否为文件表单</li>
<li>创建文件保存路径和临时文件</li>
<li>创建<code>DiskFileItemFactory</code>对象，设置缓冲区大小和临时文件目录；</li>
<li>使用DiskFileItemFactory 对象创建<code>ServletFileUpload</code>对象，并设置上传文件的大小限制；</li>
<li>调用<code>ServletFileUpload.parseRequest</code>方法解析request对象，得到一个保存了所有上传内容的List对象；</li>
<li>对list进行迭代，每迭代一个<code>FileItem</code>对象，调用其<code>isFormField</code>方法判断是否是上传文件；如果为普通表单字段，则调用<code>getFieldName</code>、<code>getString</code>方法得到字段名和字段值；如果为上传文件，则调用<code>getInputStream</code>方法得到数据输入流，从而读取上传数据</li>
</ul>
<h2 id="细节处理"><a href="#细节处理" class="headerlink" title="细节处理"></a>细节处理</h2><ul>
<li><p>中文文件乱码问题</p>
<ul>
<li>文件名中文乱码问题，可调用<code>ServletUpLoader</code>的<code>setHeaderEncoding</code>方法，或者设置<code>request</code>的<code>setCharacterEncoding</code>属性</li>
</ul>
</li>
<li><p>临时文件的删除问题</p>
<ul>
<li>由于文件大小超出DiskFileItemFactory.setSizeThreshold方法设置的内存缓冲区的大小时，Commons-fileupload组件将使用临时文件保存上传数据，因此在程序结束时，务必调用<code>FileItem.delete</code>方法删除临时文件；</li>
<li>Delete方法的调用必须位于流关闭之后，否则会出现文件占用，而导致删除失败的情况；</li>
</ul>
</li>
<li><p>文件上传注意事项</p>
<ul>
<li>为保证服务器的安全，上传的文件应放在外界无法访问的目录下，如WEN-INF</li>
<li>为防止同名文件产生覆盖现象，要为文件指定一个唯一的文件名</li>
<li>要对上传文件的大小进行限制</li>
<li>限制上传文件的类型，收到文件时，判断文件名十分合法</li>
</ul>
</li>
<li><p>显示上传进度</p>
</li>
<li><p>ProgressListener显示上传进度</p>
</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">ProgressListener progressListener = <span class="keyword">new</span> ProgressListener() &#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">update</span><span class="params">(<span class="keyword">long</span> pBytesRead, <span class="keyword">long</span> pContentLength, <span class="keyword">int</span> pItems)</span> </span>&#123;</span><br><span class="line">        System.out.println(<span class="string">&quot;到现在为止,  &quot;</span> + pBytesRead + <span class="string">&quot; 字节已上传，总大小为 &quot;</span></span><br><span class="line">              + pContentLength);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;;</span><br><span class="line">upload.setProgressListener(progressListener);</span><br></pre></td></tr></table></figure>

<ul>
<li>以KB为单位显示上传进度</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">long</span> temp = -<span class="number">1</span>;   <span class="comment">//temp注意设置为类变量</span></span><br><span class="line"><span class="keyword">long</span> ctemp = pBytesRead /<span class="number">1024</span>; </span><br><span class="line"><span class="keyword">if</span> (mBytes == ctemp)  </span><br><span class="line">    <span class="keyword">return</span>; </span><br><span class="line">temp = mBytes; </span><br></pre></td></tr></table></figure>

<h2 id="编码实现"><a href="#编码实现" class="headerlink" title="编码实现"></a>编码实现</h2><ul>
<li>fileupload.jsp前端页面</li>
</ul>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">%@</span> <span class="attr">page</span> <span class="attr">contentType</span>=<span class="string">&quot;text/html;charset=UTF-8&quot;</span> <span class="attr">language</span>=<span class="string">&quot;java&quot;</span> %&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">%@</span> <span class="attr">page</span> <span class="attr">isELIgnored</span>=<span class="string">&quot;false&quot;</span>%&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">html</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">head</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">title</span>&gt;</span>$Title$<span class="tag">&lt;/<span class="name">title</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">head</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">body</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;<span class="name">%--</span>  通过表单上传文件</span></span><br><span class="line"><span class="tag">      <span class="attr">get</span>：上传文件的大小有限制</span></span><br><span class="line"><span class="tag">      <span class="attr">post</span>：上传文件的大小没有限制</span></span><br><span class="line"><span class="tag"><span class="attr">--</span>%&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;<span class="name">form</span> <span class="attr">action</span>=<span class="string">&quot;$&#123;pageContext.request.contextPath&#125;/FileUploadServlet&quot;</span> <span class="attr">method</span>=<span class="string">&quot;post&quot;</span> <span class="attr">enctype</span>=<span class="string">&quot;multipart/form-data&quot;</span>&gt;</span></span><br><span class="line">    上传用户：<span class="tag">&lt;<span class="name">input</span> <span class="attr">type</span>=<span class="string">&quot;text&quot;</span> <span class="attr">name</span>=<span class="string">&quot;username&quot;</span>&gt;</span> <span class="tag">&lt;<span class="name">br</span>/&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">p</span>&gt;</span><span class="tag">&lt;<span class="name">input</span> <span class="attr">type</span>=<span class="string">&quot;file&quot;</span> <span class="attr">name</span>=<span class="string">&quot;file1&quot;</span>&gt;</span><span class="tag">&lt;/<span class="name">p</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">p</span>&gt;</span><span class="tag">&lt;<span class="name">input</span> <span class="attr">type</span>=<span class="string">&quot;file&quot;</span> <span class="attr">name</span>=<span class="string">&quot;file2&quot;</span>&gt;</span><span class="tag">&lt;/<span class="name">p</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">p</span>&gt;</span><span class="tag">&lt;<span class="name">input</span> <span class="attr">type</span>=<span class="string">&quot;submit&quot;</span>&gt;</span> | <span class="tag">&lt;<span class="name">input</span> <span class="attr">type</span>=<span class="string">&quot;reset&quot;</span>&gt;</span><span class="tag">&lt;/<span class="name">p</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">form</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;/<span class="name">body</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">html</span>&gt;</span></span><br></pre></td></tr></table></figure>


<h3 id="主方法"><a href="#主方法" class="headerlink" title="主方法"></a>主方法</h3><ul>
<li>FileUploadServlet用于处理发送的请求</li>
<li>采用封装的思想，把每一步的实现用方法封装，然后调用</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.lzy.file;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> org.apache.commons.fileupload.FileItem;</span><br><span class="line"><span class="keyword">import</span> org.apache.commons.fileupload.FileUploadException;</span><br><span class="line"><span class="keyword">import</span> org.apache.commons.fileupload.ProgressListener;</span><br><span class="line"><span class="keyword">import</span> org.apache.commons.fileupload.disk.DiskFileItemFactory;</span><br><span class="line"><span class="keyword">import</span> org.apache.commons.fileupload.servlet.ServletFileUpload;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> javax.servlet.ServletException;</span><br><span class="line"><span class="keyword">import</span> javax.servlet.http.HttpServlet;</span><br><span class="line"><span class="keyword">import</span> javax.servlet.http.HttpServletRequest;</span><br><span class="line"><span class="keyword">import</span> javax.servlet.http.HttpServletResponse;</span><br><span class="line"><span class="keyword">import</span> java.io.*;</span><br><span class="line"><span class="keyword">import</span> java.util.List;</span><br><span class="line"><span class="keyword">import</span> java.util.UUID;</span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">FileUploadServlet</span> <span class="keyword">extends</span> <span class="title">HttpServlet</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">doPost</span><span class="params">(HttpServletRequest req, HttpServletResponse resp)</span> <span class="keyword">throws</span> ServletException, IOException </span>&#123;</span><br><span class="line"></span><br><span class="line">        <span class="comment">//创建上传文件的保存路径，建议保存在WEB-INF路径下，安全，用户无法直接访问上传的文件；</span></span><br><span class="line">        String uploadPath = <span class="keyword">this</span>.getServletContext().getRealPath(<span class="string">&quot;WEB-INF/upload&quot;</span>);</span><br><span class="line">        File uploadFile = <span class="keyword">new</span> File(uploadPath);</span><br><span class="line">        <span class="keyword">if</span> (!uploadFile.exists()) &#123;</span><br><span class="line">            uploadFile.mkdir(); <span class="comment">//创建这个目录</span></span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="comment">//缓存，临时文件</span></span><br><span class="line">        <span class="comment">//临时路径，假如文件超过了预期大小，我们就该把他放到一个临时的文件中，过几天自动删除，或者提醒用户转存为永久</span></span><br><span class="line">        String tmpPath = <span class="keyword">this</span>.getServletContext().getRealPath(<span class="string">&quot;WEB-INF/tmp&quot;</span>);</span><br><span class="line">        File tmpFile = <span class="keyword">new</span> File(tmpPath);</span><br><span class="line">        <span class="keyword">if</span> (!tmpFile.exists()) &#123;</span><br><span class="line">            tmpFile.mkdir(); <span class="comment">//创建这个目录</span></span><br><span class="line">            System.out.println(<span class="string">&quot;创建了没有==============&quot;</span>);</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            <span class="comment">//1.创建DiskFileItemFactory对象,处理文件上传路径或者大小限制的</span></span><br><span class="line">            DiskFileItemFactory factory = getDiskFileItemFactory(tmpFile);</span><br><span class="line">            <span class="comment">//2.获取ServletFileUpload,设置上传文件的大小限制；</span></span><br><span class="line">            ServletFileUpload upload = getServletFileUpload(factory);</span><br><span class="line">            <span class="comment">//处理上传文件</span></span><br><span class="line">            String msg = uploadParseRequest(upload, req, uploadPath);</span><br><span class="line">            <span class="comment">//servlet请求消息转发,用于发送结果信息</span></span><br><span class="line">            req.setAttribute(<span class="string">&quot;msg&quot;</span>, msg);</span><br><span class="line">            req.getRequestDispatcher(<span class="string">&quot;info.jsp&quot;</span>).forward(req, resp);</span><br><span class="line"></span><br><span class="line">        &#125; <span class="keyword">catch</span> (FileUploadException e) &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="getDiskFileItemFactory"><a href="#getDiskFileItemFactory" class="headerlink" title="getDiskFileItemFactory"></a>getDiskFileItemFactory</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> DiskFileItemFactory <span class="title">getDiskFileItemFactory</span><span class="params">(File file)</span> </span>&#123;</span><br><span class="line">        DiskFileItemFactory factory = <span class="keyword">new</span> DiskFileItemFactory();</span><br><span class="line">        <span class="comment">//通过这个工厂设置一个缓冲区，当上传的文件大于这个缓冲区的时候，将它放到临时文件中；</span></span><br><span class="line">        factory.setSizeThreshold(<span class="number">1024</span> * <span class="number">1024</span>); <span class="comment">//缓存区大小为1M</span></span><br><span class="line">        factory.setRepository(file); <span class="comment">//临时目录的保存目录，需要一个tmpFile</span></span><br><span class="line">        <span class="keyword">return</span> factory;</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>

<h3 id="getServletFileUpload"><a href="#getServletFileUpload" class="headerlink" title="getServletFileUpload("></a>getServletFileUpload(</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> ServletFileUpload <span class="title">getServletFileUpload</span><span class="params">(DiskFileItemFactory factory)</span> </span>&#123;</span><br><span class="line">        ServletFileUpload upload = <span class="keyword">new</span> ServletFileUpload(factory);</span><br><span class="line">        <span class="comment">//监听文件上传进度：</span></span><br><span class="line">        upload.setProgressListener(<span class="keyword">new</span> ProgressListener() &#123;</span><br><span class="line">            <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">update</span><span class="params">(<span class="keyword">long</span> pBytesRead, <span class="keyword">long</span> pContentLength, <span class="keyword">int</span> pItems)</span> </span>&#123;</span><br><span class="line">                System.out.println(<span class="string">&quot;总大小：&quot;</span> + pContentLength + <span class="string">&quot;已上传：&quot;</span> + pBytesRead);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//处理乱码问题</span></span><br><span class="line">        upload.setHeaderEncoding(<span class="string">&quot;UTF-8&quot;</span>);</span><br><span class="line">        <span class="comment">//设置单个文件的最大值</span></span><br><span class="line">        upload.setFileSizeMax(<span class="number">1024</span> * <span class="number">1024</span> * <span class="number">10</span>);</span><br><span class="line">        <span class="comment">//设置总共能够上传文件的大小</span></span><br><span class="line">        upload.setFileSizeMax(<span class="number">1024</span> * <span class="number">1024</span> * <span class="number">10</span>);</span><br><span class="line"></span><br><span class="line">        <span class="keyword">return</span> upload;</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>
<h3 id="uploadParseRequest"><a href="#uploadParseRequest" class="headerlink" title="uploadParseRequest"></a>uploadParseRequest</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> String <span class="title">uploadParseRequest</span><span class="params">(ServletFileUpload upload, HttpServletRequest req, String uploadPath)</span> <span class="keyword">throws</span> IOException, FileUploadException </span>&#123;</span><br><span class="line">       String msg = <span class="string">&quot;&quot;</span>;</span><br><span class="line"></span><br><span class="line">       <span class="comment">//把前端请求解析，封装成一个FileItem对象</span></span><br><span class="line">       List&lt;FileItem&gt; fileItems = upload.parseRequest(req);</span><br><span class="line">       <span class="comment">//fileItem每一个表单对象</span></span><br><span class="line">       <span class="keyword">for</span> (FileItem fileItem : fileItems) &#123;</span><br><span class="line">           <span class="keyword">if</span> (fileItem.isFormField()) &#123; <span class="comment">//判断上传的文件是普通的表单还是带文件的表单</span></span><br><span class="line">               <span class="comment">//getFileName指的是前端表单控件的name</span></span><br><span class="line">               String name = fileItem.getFieldName();</span><br><span class="line">               String value = fileItem.getString(<span class="string">&quot;UTF-8&quot;</span>); <span class="comment">//处理乱码问题</span></span><br><span class="line">               System.out.println(name + <span class="string">&quot;:&quot;</span> + value);</span><br><span class="line">           &#125; <span class="keyword">else</span> &#123; <span class="comment">//判断它是上传的文件</span></span><br><span class="line"></span><br><span class="line">               <span class="comment">//====================处理文件=================//</span></span><br><span class="line"></span><br><span class="line">               <span class="comment">//拿到文件名字</span></span><br><span class="line">               String uploadFileName = fileItem.getName();</span><br><span class="line">               System.out.println(<span class="string">&quot;上传的文件名：&quot;</span> + uploadFileName);</span><br><span class="line">               <span class="comment">//可能存在文件名不合法的情况</span></span><br><span class="line">               <span class="keyword">if</span> (uploadFileName.trim().equals(<span class="string">&quot;&quot;</span>) || uploadFileName == <span class="keyword">null</span>) &#123;</span><br><span class="line">                   <span class="keyword">continue</span>;</span><br><span class="line">               &#125;</span><br><span class="line"></span><br><span class="line">               <span class="comment">//获得上传的文件名 /images/girl/bilibili.png</span></span><br><span class="line">               String fileName = uploadFileName.substring(uploadFileName.lastIndexOf(<span class="string">&quot;/&quot;</span>) + <span class="number">1</span>);</span><br><span class="line">               <span class="comment">//获得文件的后缀名</span></span><br><span class="line">               String fileExtName = uploadFileName.substring(uploadFileName.lastIndexOf(<span class="string">&quot;.&quot;</span>) + <span class="number">1</span>);</span><br><span class="line">                   <span class="comment">/*</span></span><br><span class="line"><span class="comment">                   如果文件后缀名 fileExtName 不是我们所需要的</span></span><br><span class="line"><span class="comment">                   就直接return，不处理，告诉用户文件类型不对</span></span><br><span class="line"><span class="comment">                    */</span></span><br><span class="line"></span><br><span class="line">               System.out.println(<span class="string">&quot;文件信息[件名：&quot;</span> + fileName + <span class="string">&quot;---文件类型&quot;</span> + fileExtName + <span class="string">&quot;]&quot;</span>);</span><br><span class="line"></span><br><span class="line">               <span class="comment">//可以使用UUID（唯一识别的通用码），保证文件名唯一；</span></span><br><span class="line">               <span class="comment">//UUID.randomUUID()，随机生成一个唯一识别的通用码；</span></span><br><span class="line"></span><br><span class="line">               <span class="comment">//网络传输中的东西，都需要序列化</span></span><br><span class="line">               <span class="comment">//POJO，实体类，如果想要在多个点奶上运行，  传输==&gt;需要把对象都序列化了</span></span><br><span class="line">               <span class="comment">//JNI = Java Native Interface</span></span><br><span class="line">               <span class="comment">//implement Serializable ： 标记接口， JVM---&gt;本地方法栈 native --&gt; C++</span></span><br><span class="line"></span><br><span class="line">               String uuidPath = UUID.randomUUID().toString();</span><br><span class="line"></span><br><span class="line">               <span class="comment">//====================处理文件完毕=================//</span></span><br><span class="line"></span><br><span class="line">               <span class="comment">//====================存放地址=================//</span></span><br><span class="line"></span><br><span class="line">               <span class="comment">//存到哪？ uploadPath</span></span><br><span class="line">               <span class="comment">//文件真实存在的路径 realPath</span></span><br><span class="line">               String realPath = uploadPath + <span class="string">&quot;/&quot;</span> + uuidPath;</span><br><span class="line">               <span class="comment">//给每个文件创建一个对应的文件夹</span></span><br><span class="line">               File realPathFile = <span class="keyword">new</span> File(realPath);</span><br><span class="line">               <span class="keyword">if</span> (!realPathFile.exists()) &#123;</span><br><span class="line">                   realPathFile.mkdir();</span><br><span class="line">               &#125;</span><br><span class="line"></span><br><span class="line">               <span class="comment">//====================文件传输=================//</span></span><br><span class="line"></span><br><span class="line">               <span class="comment">//获得文件上传的流</span></span><br><span class="line">               InputStream inputStream = fileItem.getInputStream();</span><br><span class="line"></span><br><span class="line">               <span class="comment">//创建一个文件输出流</span></span><br><span class="line">               <span class="comment">//realPath = 真实的文件夹</span></span><br><span class="line">               <span class="comment">//差了一个文件；加上输出文件的名字 + &quot;/&quot; + uuidFileName</span></span><br><span class="line">               FileOutputStream fos = <span class="keyword">new</span> FileOutputStream(realPath + <span class="string">&quot;/&quot;</span> + fileName);</span><br><span class="line"></span><br><span class="line">               <span class="comment">//创建一个缓冲区</span></span><br><span class="line">               <span class="keyword">byte</span>[] buffer = <span class="keyword">new</span> <span class="keyword">byte</span>[<span class="number">1024</span> * <span class="number">1024</span>];</span><br><span class="line"></span><br><span class="line">               <span class="comment">//判断是否读取完毕</span></span><br><span class="line">               <span class="keyword">int</span> len = <span class="number">0</span>;</span><br><span class="line">               <span class="comment">//如果大于0说明还在存数据</span></span><br><span class="line">               <span class="keyword">while</span> ((len = inputStream.read(buffer)) &gt; <span class="number">0</span>) &#123;</span><br><span class="line">                   fos.write(buffer, <span class="number">0</span>, len);</span><br><span class="line">               &#125;</span><br><span class="line"></span><br><span class="line">               <span class="comment">//关闭流</span></span><br><span class="line">               fos.close();</span><br><span class="line">               inputStream.close();</span><br><span class="line"></span><br><span class="line">               msg = <span class="string">&quot;文件上传成功！&quot;</span>;</span><br><span class="line">               fileItem.delete(); <span class="comment">//上传成功，清除临时文件</span></span><br><span class="line"></span><br><span class="line">           &#125;</span><br><span class="line"></span><br><span class="line">       &#125;</span><br><span class="line">       <span class="keyword">return</span> msg;</span><br><span class="line">   &#125;</span><br></pre></td></tr></table></figure>

<h2 id="运行结果"><a href="#运行结果" class="headerlink" title="运行结果"></a>运行结果</h2><p><img src="https://cdn.jsdelivr.net/gh/xiaoliblog/image@51bd21f71f36aad0c79a51a3557ee68f6265112c/2021/03/27/8f5f37c487234d1710c3f087bf5636cb.png"><br><img src="https://cdn.jsdelivr.net/gh/xiaoliblog/image@bfc16bc8afa4c88117f8ca1bf14ba27971be6e81/2021/03/27/d4d94d6047710e1f7ffa49576fe7b04d.png"><br><img src="https://cdn.jsdelivr.net/gh/xiaoliblog/image@c506237a1768eefc9e649c34f6abc9806a17df98/2021/03/27/8bac0ce3ddb3e463193e41740db72873.png"></p>
<h1 id="文件下载"><a href="#文件下载" class="headerlink" title="文件下载"></a>文件下载</h1><h2 id="文件下载概述"><a href="#文件下载概述" class="headerlink" title="文件下载概述"></a>文件下载概述</h2><ul>
<li>程序实现下载需设置两个响应头，</li>
<li>设置<code>Content-Typ</code> 的值为：<code>application/x-msdownload</code><ul>
<li>Web 服务器需要告诉浏览器其所输出的内容的类型不是普通的文本文件或 HTML 文件，而是一个要保存到本地的下载文件；</li>
</ul>
</li>
<li>Web 服务器希望浏览器不直接处理相应的实体内容，而是由用户选择将相应的实体内容保存到一个文件中，这需要设置 <code>Content-Disposition</code> 报头<ul>
<li>该报头指定了接收程序处理数据内容的方式，在 HTTP 应用中只有 attachment 是标准方式，attachment 表示要求用户干预。在 attachment 后面还可以指定 filename 参数，该参数是服务器建议浏览器将实体内容保存到文件中的文件名称。在设置 Content-Dispostion 之前一定要指定 Content-Type</li>
</ul>
</li>
<li>因为要下载的文件可以是各种类型的文件，所以要将文件传送给客户端，其相应内容应该被当做二进制来处理，所以应该调用<code>response.getOutputStream()</code>方法返回 ServeltOutputStream 对象来向客户端写入文件内容</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">response.setContentType(<span class="string">&quot;application/x-msdownload&quot;</span>) ;</span><br><span class="line">String str = <span class="string">&quot;attachment;filename=&quot;</span> + java.net.URLEncoder.encode(fileName, <span class="string">&quot;UTF-8&quot;</span>) ;</span><br><span class="line">response.setHeader(<span class="string">&quot;Content-Disposition&quot;</span>, str) ;</span><br></pre></td></tr></table></figure>

<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">InputStream is = <span class="keyword">new</span> FileInputStream(file) ;</span><br><span class="line">OutputStream os = response.getOutputStream() ;</span><br><span class="line"><span class="keyword">int</span> len = -<span class="number">1</span> ;</span><br><span class="line"><span class="keyword">byte</span>[] buf = <span class="keyword">new</span> <span class="keyword">byte</span>[<span class="number">1024</span>] ;</span><br><span class="line"><span class="keyword">while</span>((len = is.read(buf)) != -<span class="number">1</span>) &#123;</span><br><span class="line">    os.write(buf, <span class="number">0</span>, len) ;</span><br><span class="line">    os.flush() ;</span><br><span class="line">&#125;</span><br><span class="line">is.close() ;</span><br><span class="line">os.close() ;</span><br></pre></td></tr></table></figure>

<h2 id="下载案例"><a href="#下载案例" class="headerlink" title="下载案例"></a>下载案例</h2><ul>
<li><p>在开发项目中，有时候需要从服务端下载一个文件到本地，以此对这需求可以使用Response对象（HttpServletResponse）就可以实现文件的下载。（注：使用的服务器是tomcat）</p>
</li>
<li><p>下载文件实现思路</p>
<ol>
<li>要获取下载文件的路径（用<code>ServletContext</code>的<code>getRealPath</code>方法获取+resources/Student.txt）</li>
<li>获取下载的文件名</li>
<li>再设置响应头(<code>content-disposition</code>)控制浏览器以下载的形式打开文件</li>
<li>然后使用<code>InputStream</code>获取下载的文件的输入流</li>
<li>创建数据缓冲区</li>
<li>通过response对象获取<code>OutputStream</code>流</li>
<li>将FileInputStream流写入byte数组即buffer缓存区</li>
<li>使用OutpuStream将byte数组的数据输出到浏览器</li>
</ol>
</li>
<li><p>在<code>resources</code>文件夹下创建一个<code>Student.txt</code>的文件·</p>
</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.lzy.JavaWeb;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> javax.servlet.ServletException;</span><br><span class="line"><span class="keyword">import</span> javax.servlet.ServletOutputStream;</span><br><span class="line"><span class="keyword">import</span> javax.servlet.http.HttpServlet;</span><br><span class="line"><span class="keyword">import</span> javax.servlet.http.HttpServletRequest;</span><br><span class="line"><span class="keyword">import</span> javax.servlet.http.HttpServletResponse;</span><br><span class="line"><span class="keyword">import</span> java.io.FileInputStream;</span><br><span class="line"><span class="keyword">import</span> java.io.IOException;</span><br><span class="line"><span class="keyword">import</span> java.io.InputStream;</span><br><span class="line"><span class="keyword">import</span> java.io.OutputStream;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">FileServlet</span> <span class="keyword">extends</span> <span class="title">HttpServlet</span> </span>&#123;</span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">doGet</span><span class="params">(HttpServletRequest req, HttpServletResponse resp)</span> <span class="keyword">throws</span> ServletException, IOException </span>&#123;</span><br><span class="line">        <span class="comment">//1.获取下载的文件路径（注意获取这里获取的是绝对路径，先获取ServletContext再使用ServletContext的getRealPath方法获取绝对路径）</span></span><br><span class="line">        String realPath = <span class="keyword">this</span>.getServletContext().getRealPath(<span class="string">&quot;/resources/Student.txt&quot;</span>);</span><br><span class="line">        System.out.println(<span class="string">&quot;下载文件第路径:&quot;</span>+realPath);</span><br><span class="line">        <span class="comment">//2. 获取下载的文件名，通过字符串截取</span></span><br><span class="line">        String fileName = realPath.substring(realPath.lastIndexOf(<span class="string">&quot;\\&quot;</span>) + <span class="number">1</span>);</span><br><span class="line">        System.out.println(fileName);</span><br><span class="line">        <span class="comment">//3. 再设置响应头(content-disposition)控制浏览器以下载的形式打开文件</span></span><br><span class="line">        resp.setHeader(<span class="string">&quot;Content-Disposition&quot;</span>, <span class="string">&quot;attachment; filename=&quot;</span>+ fileName);</span><br><span class="line">        InputStream in=<span class="keyword">null</span>;</span><br><span class="line">        OutputStream out=<span class="keyword">null</span>;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            <span class="comment">//4. 然后使用InputStream获取下载的文件的输入流</span></span><br><span class="line">            in=<span class="keyword">new</span> FileInputStream(realPath);</span><br><span class="line">            <span class="comment">//5. 创建数据缓冲区</span></span><br><span class="line">            <span class="keyword">int</span> len=<span class="number">0</span>;</span><br><span class="line">            <span class="keyword">byte</span> buffer[]=<span class="keyword">new</span> <span class="keyword">byte</span>[<span class="number">1024</span>];</span><br><span class="line">            <span class="comment">//6. 通过response对象获取OutputStream流</span></span><br><span class="line">            out=resp.getOutputStream();</span><br><span class="line">            <span class="comment">//7. 将FileInputStream流写入byte数组即buffer缓存区</span></span><br><span class="line">            <span class="keyword">while</span>((len=in.read(buffer))!=-<span class="number">1</span>)&#123;</span><br><span class="line">                <span class="comment">//8. 使用OutpuStream将byte数组的数据输出到浏览器</span></span><br><span class="line">                out.write(buffer,<span class="number">0</span>,len);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125;<span class="keyword">finally</span> &#123;</span><br><span class="line">            <span class="keyword">if</span>(in!=<span class="keyword">null</span>)&#123;</span><br><span class="line">                in.close();</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<ul>
<li>运行结果</li>
</ul>
<img src="https://cdn.jsdelivr.net/gh/xiaoliblog/image@e47552b41a4ce5c44506576e65632f2795aebbe5/2021/03/22/14634e9969fdc2be46fb381c5d2368cb.png" width="50%">

<h1 id="参考"><a href="#参考" class="headerlink" title="参考"></a>参考</h1><div class="note success simple"><p>👉<a target="_blank" rel="noopener" href="https://blog.csdn.net/u010445297/article/details/62230044">JavaWeb之文件上传与下载详解</a><br>👉<a target="_blank" rel="noopener" href="https://www.jb51.net/article/96745.htm">JavaWeb实现文件上传下载功能实例详解</a></p>
</div></article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="mailto:undefined">小李博客</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="https://xiaoliblog.cn">https://xiaoliblog.cn</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="http://xiaoliblog.cn" target="_blank">小李博客</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/JavaWeb/">JavaWeb</a></div><div class="post_share"><div class="social-share" data-image="https://cdn.jsdelivr.net/gh/xiaoliblog/image@41021477288a29257324f7413b81c299b3dec54e/2021/03/21/3d05e9b134d98fc70cebf887c1359f71.png" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/social-share.js/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/social-share.js/dist/js/social-share.min.js" defer></script></div></div><div class="post-reward"><div class="reward-button button--animated"><i class="fas fa-qrcode"></i> 打赏</div><div class="reward-main"><ul class="reward-all"><li class="reward-item"><a href="/img/wechat.png" target="_blank"><img class="post-qr-code-img" src="/img/wechat.png" alt="微信"/></a><div class="post-qr-code-desc">微信</div></li><li class="reward-item"><a href="/img/alipay.png" target="_blank"><img class="post-qr-code-img" src="/img/alipay.png" alt="支付宝"/></a><div class="post-qr-code-desc">支付宝</div></li></ul></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/page/JavaWeb13.html"><img class="prev-cover" src="https://cdn.jsdelivr.net/gh/xiaoliblog/image@41021477288a29257324f7413b81c299b3dec54e/2021/03/21/3d05e9b134d98fc70cebf887c1359f71.png" onerror="onerror=null;src='https://cdn.jsdelivr.net/gh/lzyblog/image@main/2020/11/19/bd16b394f7359083b1f6072a67e3f968.png'" alt="cover of previous post"><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">JavaWeb🌍分页功能</div></div></a></div><div class="next-post pull-right"><a href="/page/JavaWeb11.html"><img class="next-cover" src="https://cdn.jsdelivr.net/gh/xiaoliblog/image@41021477288a29257324f7413b81c299b3dec54e/2021/03/21/3d05e9b134d98fc70cebf887c1359f71.png" onerror="onerror=null;src='https://cdn.jsdelivr.net/gh/lzyblog/image@main/2020/11/19/bd16b394f7359083b1f6072a67e3f968.png'" alt="cover of next post"><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">JavaWeb🌍Frame框架</div></div></a></div></nav><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span> 相关推荐</span></div><div class="relatedPosts-list"><div><a href="/page/JavaWeb10.html" title="JavaWeb🌍Ajax异步检测"><img class="cover" src="https://cdn.jsdelivr.net/gh/xiaoliblog/image@41021477288a29257324f7413b81c299b3dec54e/2021/03/21/3d05e9b134d98fc70cebf887c1359f71.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-01-15</div><div class="title">JavaWeb🌍Ajax异步检测</div></div></a></div><div><a href="/page/JavaWeb11.html" title="JavaWeb🌍Frame框架"><img class="cover" src="https://cdn.jsdelivr.net/gh/xiaoliblog/image@41021477288a29257324f7413b81c299b3dec54e/2021/03/21/3d05e9b134d98fc70cebf887c1359f71.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-01-15</div><div class="title">JavaWeb🌍Frame框架</div></div></a></div><div><a href="/page/JavaWeb06.html" title="JavaWeb🌍EL表达式"><img class="cover" src="https://cdn.jsdelivr.net/gh/xiaoliblog/image@41021477288a29257324f7413b81c299b3dec54e/2021/03/21/3d05e9b134d98fc70cebf887c1359f71.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-01-15</div><div class="title">JavaWeb🌍EL表达式</div></div></a></div><div><a href="/page/JavaWeb07.html" title="JavaWeb🌍JSTL标签"><img class="cover" src="https://cdn.jsdelivr.net/gh/xiaoliblog/image@41021477288a29257324f7413b81c299b3dec54e/2021/03/21/3d05e9b134d98fc70cebf887c1359f71.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-01-15</div><div class="title">JavaWeb🌍JSTL标签</div></div></a></div><div><a href="/page/JavaWeb18.html" title="JavaWeb🌍smbms注销及权限过滤"><img class="cover" src="https://cdn.jsdelivr.net/gh/xiaoliblog/image@41021477288a29257324f7413b81c299b3dec54e/2021/03/21/3d05e9b134d98fc70cebf887c1359f71.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-01-18</div><div class="title">JavaWeb🌍smbms注销及权限过滤</div></div></a></div><div><a href="/page/JavaWeb16.html" title="JavaWeb🌍smbms项目搭建"><img class="cover" src="https://cdn.jsdelivr.net/gh/xiaoliblog/image@41021477288a29257324f7413b81c299b3dec54e/2021/03/21/3d05e9b134d98fc70cebf887c1359f71.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-01-16</div><div class="title">JavaWeb🌍smbms项目搭建</div></div></a></div></div></div><hr/><div id="post-comment"><div class="comment-head"><div class="comment-headline"><i class="fas fa-comments fa-fw"></i><span> 评论</span></div></div><div class="comment-wrap"><div><div id="twikoo-wrap"></div></div></div></div></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="card-info-avatar is-center"><img class="avatar-img" src="https://cdn.jsdelivr.net/gh/xiaoliblog/image@6b5e7ef72be1c8973d94e5a9c49accbf775ad820/2021/02/01/c485da031fe0e464d04eaba8a66c4a8f.png" onerror="this.onerror=null;this.src='/img/friend_404.gif'" alt="avatar"/><div class="author-info__name">小李博客</div><div class="author-info__description">越努力，越幸运！</div></div><div class="card-info-data"><div class="card-info-data-item is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">210</div></a></div><div class="card-info-data-item is-center"><a href="/tags/"><div class="headline">标签</div><div class="length-num">38</div></a></div><div class="card-info-data-item is-center"><a href="/categories/"><div class="headline">分类</div><div class="length-num">56</div></a></div></div><a class="button--animated" id="card-info-btn" target="_blank" rel="noopener" href="https://github.com/xiaoliblog"><i class="fab fa-github"></i><span>博主的GitHub首页</span></a><div class="card-info-social-icons is-center"><a class="social-icon" href="https://gitee.com/xiaoliblog" target="_blank" title="Gitee"><i class="iconfont icon-gitee card_icon_gitee"></i></a><a class="social-icon" href="https://space.bilibili.com/390969485" target="_blank" title="BiliBili"><i class="iconfont icon-bilibili card_icon_bilibili"></i></a><a class="social-icon" href="http://wpa.qq.com/msgrd?v=3&amp;uin=2312057536&amp;site=CSDN&amp;menu=yes" target="_blank" title="QQ"><i class="iconfont icon-qq card_icon_qq"></i></a><a class="social-icon" href="https://github.com/xiaoliblog" target="_blank" title="GitHub"><i class="iconfont icon-git card_icon_git"></i></a><a class="social-icon" href="https://blog.csdn.net/qq_43266250?spm=1010.2135.3001.5113" target="_blank" title="CSDN"><i class="iconfont icon-csdn card_icon_csdn"></i></a></div></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn card-announcement-animation"></i><span>公告</span></div><div class="announcement_content">正在考研备考中💦</div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#%E6%96%87%E4%BB%B6%E4%B8%8A%E4%BC%A0"><span class="toc-number">1.</span> <span class="toc-text">文件上传</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%96%87%E4%BB%B6%E4%B8%8A%E4%BC%A0%E6%A6%82%E8%BF%B0"><span class="toc-number">1.1.</span> <span class="toc-text">文件上传概述</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%87%86%E5%A4%87%E5%B7%A5%E4%BD%9C"><span class="toc-number">1.2.</span> <span class="toc-text">准备工作</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#fileupload%E5%B7%A5%E4%BD%9C%E6%B5%81%E7%A8%8B"><span class="toc-number">2.</span> <span class="toc-text">fileupload工作流程</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#fileupload%E6%A0%B8%E5%BF%83API"><span class="toc-number">3.</span> <span class="toc-text">fileupload核心API</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#DiskFileItemFactory%E5%B7%A5%E5%8E%82%E7%B1%BB"><span class="toc-number">3.1.</span> <span class="toc-text">DiskFileItemFactory工厂类</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#ServletFileUpload%E8%A7%A3%E6%9E%90%E5%99%A8"><span class="toc-number">3.2.</span> <span class="toc-text">ServletFileUpload解析器</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#FileItem%E8%A1%A8%E5%8D%95%E5%AD%97%E6%AE%B5%E5%9F%9F%E5%AF%B9%E8%B1%A1"><span class="toc-number">3.3.</span> <span class="toc-text">FileItem表单字段域对象</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E6%96%87%E4%BB%B6%E4%B8%8A%E4%BC%A0%E6%A1%88%E4%BE%8B"><span class="toc-number">4.</span> <span class="toc-text">文件上传案例</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%AE%9E%E7%8E%B0%E6%AD%A5%E9%AA%A4"><span class="toc-number">4.1.</span> <span class="toc-text">实现步骤</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E7%BB%86%E8%8A%82%E5%A4%84%E7%90%86"><span class="toc-number">4.2.</span> <span class="toc-text">细节处理</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E7%BC%96%E7%A0%81%E5%AE%9E%E7%8E%B0"><span class="toc-number">4.3.</span> <span class="toc-text">编码实现</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%B8%BB%E6%96%B9%E6%B3%95"><span class="toc-number">4.3.1.</span> <span class="toc-text">主方法</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#getDiskFileItemFactory"><span class="toc-number">4.3.2.</span> <span class="toc-text">getDiskFileItemFactory</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#getServletFileUpload"><span class="toc-number">4.3.3.</span> <span class="toc-text">getServletFileUpload(</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#uploadParseRequest"><span class="toc-number">4.3.4.</span> <span class="toc-text">uploadParseRequest</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E8%BF%90%E8%A1%8C%E7%BB%93%E6%9E%9C"><span class="toc-number">4.4.</span> <span class="toc-text">运行结果</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E6%96%87%E4%BB%B6%E4%B8%8B%E8%BD%BD"><span class="toc-number">5.</span> <span class="toc-text">文件下载</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%96%87%E4%BB%B6%E4%B8%8B%E8%BD%BD%E6%A6%82%E8%BF%B0"><span class="toc-number">5.1.</span> <span class="toc-text">文件下载概述</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E4%B8%8B%E8%BD%BD%E6%A1%88%E4%BE%8B"><span class="toc-number">5.2.</span> <span class="toc-text">下载案例</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E5%8F%82%E8%80%83"><span class="toc-number">6.</span> <span class="toc-text">参考</span></a></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item"><a class="thumbnail" href="/page/project01.html" title="前端实例🥳响应式网站首页"><img src="https://cdn.jsdelivr.net/gh/xiaoliblog/image@c19917500ab083c77c7613263ba7ee74d5a08ae6/2021/04/30/469f30b141d73fa0fc4c962662d5813f.png" onerror="this.onerror=null;this.src='https://cdn.jsdelivr.net/gh/lzyblog/image@main/2020/11/19/bd16b394f7359083b1f6072a67e3f968.png'" alt="前端实例🥳响应式网站首页"/></a><div class="content"><a class="title" href="/page/project01.html" title="前端实例🥳响应式网站首页">前端实例🥳响应式网站首页</a><time datetime="2021-04-30T11:50:53.094Z" title="发表于 2021-04-30 19:50:53">2021-04-30</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/page/WeChatpay.html" title="微信支付对接"><img src="https://cdn.jsdelivr.net/gh/xiaoliblog/image@f2f670b92ea149650ffa7834354fc90284f2f44a/2021/04/29/5bdc9b381a06193d27cf2fb7c2fb608a.png" onerror="this.onerror=null;this.src='https://cdn.jsdelivr.net/gh/lzyblog/image@main/2020/11/19/bd16b394f7359083b1f6072a67e3f968.png'" alt="微信支付对接"/></a><div class="content"><a class="title" href="/page/WeChatpay.html" title="微信支付对接">微信支付对接</a><time datetime="2021-04-29T12:20:48.070Z" title="发表于 2021-04-29 20:20:48">2021-04-29</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/page/Alipay.html" title="支付宝支付对接"><img src="https://cdn.jsdelivr.net/gh/xiaoliblog/image@61a9b6a6e09e4bda38bb08e3104b717885beaee5/2021/04/29/c3fa51f9cf14e90d9e5a7aa8814dd041.png" onerror="this.onerror=null;this.src='https://cdn.jsdelivr.net/gh/lzyblog/image@main/2020/11/19/bd16b394f7359083b1f6072a67e3f968.png'" alt="支付宝支付对接"/></a><div class="content"><a class="title" href="/page/Alipay.html" title="支付宝支付对接">支付宝支付对接</a><time datetime="2021-04-27T16:00:00.000Z" title="发表于 2021-04-28 00:00:00">2021-04-28</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/page/Vuejs11.html" title="Vue.js前端框架🎯Pagination+PageHelper实现分页"><img src="https://cdn.jsdelivr.net/gh/xiaoliblog/image@61bf4245f6d84d2d0f66d163b89c916788cc1845/2021/04/13/ec6b232f8fe5a840e4bd8c3eabcf49b2.png" onerror="this.onerror=null;this.src='https://cdn.jsdelivr.net/gh/lzyblog/image@main/2020/11/19/bd16b394f7359083b1f6072a67e3f968.png'" alt="Vue.js前端框架🎯Pagination+PageHelper实现分页"/></a><div class="content"><a class="title" href="/page/Vuejs11.html" title="Vue.js前端框架🎯Pagination+PageHelper实现分页">Vue.js前端框架🎯Pagination+PageHelper实现分页</a><time datetime="2021-04-26T14:48:39.701Z" title="发表于 2021-04-26 22:48:39">2021-04-26</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/page/Vuejs10.html" title="Vue.js前端框架🎯Vue-Element-admin模版"><img src="https://cdn.jsdelivr.net/gh/xiaoliblog/image@61bf4245f6d84d2d0f66d163b89c916788cc1845/2021/04/13/ec6b232f8fe5a840e4bd8c3eabcf49b2.png" onerror="this.onerror=null;this.src='https://cdn.jsdelivr.net/gh/lzyblog/image@main/2020/11/19/bd16b394f7359083b1f6072a67e3f968.png'" alt="Vue.js前端框架🎯Vue-Element-admin模版"/></a><div class="content"><a class="title" href="/page/Vuejs10.html" title="Vue.js前端框架🎯Vue-Element-admin模版">Vue.js前端框架🎯Vue-Element-admin模版</a><time datetime="2021-04-19T16:00:00.000Z" title="发表于 2021-04-20 00:00:00">2021-04-20</time></div></div></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="copyright">&copy;2020 - 2021 By 小李博客</div><div class="framework-info"><span>框架 </span><a target="_blank" rel="noopener" href="https://hexo.io">🎯Hexo</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">🎉Butterfly</a></div><div class="footer_custom_text"><span><a style="margin-inline:5px" target="_blank" href="https://hexo.io/"><img src="https://img.shields.io/badge/Frame-Hexo-blue?style=flat&logo=hexo" title="博客框架为Hexo"></a><a style="margin-inline:5px" target="_blank" href="https://butterfly.js.org/"><img src="https://img.shields.io/badge/Theme-Butterfly-6513df?style=flat&logo=bitdefender" title="主题采用butterfly"></a><a style="margin-inline:5px" target="_blank" href="https://www.jsdelivr.com/"><img src="https://img.shields.io/badge/CDN-jsDelivr-orange?style=flat&logo=jsDelivr" title="本站使用JsDelivr为静态资源提供CDN加速"></a><a style="margin-inline:5px" target="_blank" href="https://vercel.com/ "><img src="https://img.shields.io/badge/Hosted-Vercel-brightgreen?style=flat&logo=Vercel" title="本站采用双线部署，默认线路托管于Vercel"></a><a style="margin-inline:5px" target="_blank" href="https://coding.net/ "><img src="https://img.shields.io/badge/Hosted-Coding-0cedbe?style=flat&logo=Codio" title="本站采用双线部署，联通线路托管于Coding"></a><a style="margin-inline:5px" target="_blank" href="https://github.com/"><img src="https://img.shields.io/badge/Source-Github-d021d6?style=flat&logo=GitHub" title="本站项目由Gtihub托管"></a><a style="margin-inline:5px" target="_blank" href="http://creativecommons.org/licenses/by-nc-sa/4.0/"><img src="https://img.shields.io/badge/Copyright-BY--NC--SA%204.0-d42328?style=flat&logo=Claris" title="本站采用知识共享署名-非商业性使用-相同方式共享4.0国际许可协议进行许可"></a></span></div><div class="icp"><a target="_blank" rel="noopener" href="https://beian.miit.gov.cn/"><img class="icp-icon" src="/img/icp.png" alt="ICP"/><span>湘ICP备2021002541号</span></a></div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="font-plus" type="button" title="放大字体"><i class="fas fa-plus"></i></button><button id="font-minus" type="button" title="缩小字体"><i class="fas fa-minus"></i></button><button id="translateLink" type="button" title="简繁转换">繁</button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="chat_btn" type="button" title="rightside.chat_btn"><i class="fas fa-sms"></i></button><a id="to_comment" href="#post-comment" title="直达评论"><i class="fas fa-comments"></i></a><button id="go-up" type="button" title="回到顶部"><i class="fas fa-arrow-up"></i></button></div></div><div id="algolia-search"><div class="search-dialog"><div class="search-dialog__title" id="algolia-search-title">Algolia</div><div id="algolia-input-panel"><div id="algolia-search-input"></div></div><hr/><div id="algolia-search-results"><div id="algolia-hits"></div><div id="algolia-pagination"></div><div id="algolia-stats"></div></div><span class="search-close-button"><i class="fas fa-times"></i></span></div><div id="search-mask"></div></div><div><script src="/js/utils.js"></script><script src="https://cdn.jsdelivr.net/npm/vue@2.6.11"></script><script src="/js/main.js"></script><script defer src="/js/tw_cn.js"></script><script defer src="https://cdn.jsdelivr.net/npm/medium-zoom/dist/medium-zoom.min.js"></script><script src="https://cdn.jsdelivr.net/npm/instant.page/instantpage.min.js" type="module" defer></script><script defer src="https://cdn.jsdelivr.net/npm/node-snackbar/dist/snackbar.min.js"></script><script defer src="/js/search/algolia.js"></script><div class="js-pjax"><script>if (!window.MathJax) {
  window.MathJax = {
    loader: {
      source: {
        '[tex]/amsCd': '[tex]/amscd'
      }
    },
    tex: {
      inlineMath: [ ['$','$'], ["\\(","\\)"]],
      tags: 'ams'
    },
    options: {
      renderActions: {
        findScript: [10, doc => {
          for (const node of document.querySelectorAll('script[type^="math/tex"]')) {
            const display = !!node.type.match(/; *mode=display/)
            const math = new doc.options.MathItem(node.textContent, doc.inputJax[0], display)
            const text = document.createTextNode('')
            node.parentNode.replaceChild(text, node)
            math.start = {node: text, delim: '', n: 0}
            math.end = {node: text, delim: '', n: 0}
            doc.math.push(math)
          }
        }, ''],
        addClass: [200,() => {
          document.querySelectorAll('mjx-container:not([display=\'true\']').forEach( node => {
            const target = node.parentNode
            if (!target.classList.contains('has-jax')) {
              target.classList.add('mathjax-overflow')
            }
          })
        }, '', false]
      }
    }
  }
  
  const script = document.createElement('script')
  script.src = 'https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js'
  script.id = 'MathJax-script'
  script.async = true
  document.head.appendChild(script)
} else {
  MathJax.startup.document.state(0)
  MathJax.texReset()
  MathJax.typeset()
}</script><script>if (document.getElementsByClassName('mermaid').length) {
  if (window.mermaidJsLoad) mermaid.init()
  else {
    getScript('https://cdn.jsdelivr.net/npm/mermaid/dist/mermaid.min.js').then(() => {
      window.mermaidJsLoad = true
      mermaid.initialize({
        theme: 'default',
      })
      false && mermaid.init()
    })
  }
}</script><script>(()=>{
  const $countDom = document.getElementById('twikoo-count')
  const init = () => {
    twikoo.init(Object.assign({
      el: '#twikoo-wrap',
      envId: 'xiaoliblog-8gj3j5045d5b0896',
      region: ''
    }, null))
  }

  const getCount = () => {
    twikoo.getCommentsCount({
      envId: 'xiaoliblog-8gj3j5045d5b0896',
      region: '',
      urls: [window.location.pathname],
      includeReply: false
    }).then(function (res) {
      $countDom.innerText = res[0].count
    }).catch(function (err) {
      console.error(err);
    });
  }

  const loadTwikoo = (bool = false) => {
    if (typeof twikoo === 'object') {
      init()
      bool && $countDom && setTimeout(getCount,0)
    } else {
      getScript('https://cdn.jsdelivr.net/npm/twikoo@1.3.0/dist/twikoo.all.min.js').then(()=> {
        init()
        bool && $countDom && setTimeout(getCount,0)
      })
    }
  }

  if ('Twikoo' === 'Twikoo' || !true) {
    if (true) btf.loadComment(document.getElementById('twikoo-wrap'), loadTwikoo)
    else loadTwikoo(true)
  } else {
    window.loadOtherComment = () => {
      loadTwikoo()
    }
  }
})()</script></div><script defer src="//lib.baomitu.com/jquery/3.5.1/jquery.min.js"></script><script defer src="https://myhkw.cn/api/player/160561664166" id="myhk" key="160561664166" m="1"></script><div><canvas id="snow" style="position:fixed;top:0;left:0;width:100%;height:100%;z-index:99999;pointer-events:none"></canvas></div><script>const notMobile = (!(navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i)));</script><scrip async type="text/javascript" src="https://cdn.jsdelivr.net/gh/Candinya/Kratos-Rebirth@latest/source/js/snow.min.js"></scrip><scrip defer src="https://cdn.jsdelivr.net/npm/hexo-theme-volantis@latest/source/js/issues.min.js"></scrip><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script><script>var gitcalendar = new Vue({
  el: '#gitcalendar',
  data: {
    simplemode: true, 
    user: 'xiaoliblog',
    fixed: 'fixed',
    px: 'px',
    x: '',
    y: '',
    span1: '',
    span2: '',
    month: ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月'],
    monthchange: [],
    oneyearbeforeday: '',
    thisday: '',
    amonthago: '',
    aweekago: '',
    weekdatacore: 0,
    datacore: 0,
    total: 0,
    datadate: '',
    data: [],
    positionplusdata: [],
    firstweek: [],
    lastweek: [],
    beforeweek: [],
    thisweekdatacore: 0,
    mounthbeforeday: 0,
    mounthfirstindex: 0,
    crispedges: 'crispedges',
    thisdayindex: 0,
    amonthagoindex: 0,
    amonthagoweek: [],
    firstdate: [],
    first2date: [],
    montharrbefore: [],
    monthindex: 0,
    color: ['#ebedf0', '#f1f8ff', '#dbedff', '#c8e1ff', '#79b8ff', '#2188ff', '#0366d6', '#005cc5', '#044289', '#032f62', '#05264c']
  },
  methods: {
    selectStyle(data, event) {
      document.querySelector('.angle-wrapper').style.display = 'block'
      this.span1 = data.date;
      this.span2 = data.count;
      this.x = event.clientX - 100;
      this.y = event.clientY - 60
    },
    outStyle() {
      document.querySelector('.angle-wrapper').style.display = 'none'
    },
    thiscolor(x) {
      if (x === 0) {
        let i = parseInt(x / 2);
        return this.color[0]
      } else if (x < 2) {
        return this.color[1]
      } else if (x < 20) {
        let i = parseInt(x / 2);
        return this.color[i]
      } else {
        return this.color[9]
      }
    },
  }
});
var apiurl = 'python-github-calendar-api-ruby.vercel.app' ? 'https://python-github-calendar-api-ruby.vercel.app/api?' : 'https://githubapi.ryanchristian.dev/user/'
var githubapiurl = apiurl + gitcalendar.user;
//canvas绘图
function responsiveChart() {
  let c = document.getElementById("gitcanvas");
  if (c) {
    let cmessage = document.getElementById("gitmessage");
    let ctx = c.getContext("2d");
    c.width = document.getElementById("gitcalendarcanvasbox").offsetWidth;
    let linemaxwitdh = 0.96 * c.width / gitcalendar.data.length;
    c.height = 9 * linemaxwitdh;
    let lineminwitdh = 0.8 * linemaxwitdh;
    let setposition = {
      x: 0.02 * c.width,
      y: 0.025 * c.width
    };
    for (let week in gitcalendar.data) {
      weekdata = gitcalendar.data[week];
      for (let day in weekdata) {
        let dataitem = {
          date: "",
          count: "",
          x: 0,
          y: 0
        };
        gitcalendar.positionplusdata.push(dataitem);
        ctx.fillStyle = gitcalendar.thiscolor(weekdata[day].count);
        setposition.y = Math.round(setposition.y * 100) / 100;
        dataitem.date = weekdata[day].date;
        dataitem.count = weekdata[day].count;
        dataitem.x = setposition.x;
        dataitem.y = setposition.y;
        ctx.fillRect(setposition.x, setposition.y, lineminwitdh, lineminwitdh);
        setposition.y = setposition.y + linemaxwitdh
      };
      setposition.y = 0.025 * c.width;
      setposition.x = setposition.x + linemaxwitdh
    };
    ctx.font = "600  Arial";
    ctx.fillStyle = '#aaa';
    ctx.fillText("日", 0, 1.9 * linemaxwitdh);
    ctx.fillText("二", 0, 3.9 * linemaxwitdh);
    ctx.fillText("四", 0, 5.9 * linemaxwitdh);
    ctx.fillText("六", 0, 7.9 * linemaxwitdh);
    let monthindexlist = c.width / 24;
    for (let index in gitcalendar.monthchange) {
      ctx.fillText(gitcalendar.monthchange[index], monthindexlist, 0.7 * linemaxwitdh);
      monthindexlist = monthindexlist + c.width / 12
    };
    cmessage.onmousemove = function(event) {
      document.querySelector('.angle-wrapper').style.display = 'none'
    };
    c.onmousemove = function(event) {
      document.querySelector('.angle-wrapper').style.display = 'none'
      getMousePos(c, event);
    };

    function getMousePos(canvas, event) {
      var rect = canvas.getBoundingClientRect();
      var x = event.clientX - rect.left * (canvas.width / rect.width);
      var y = event.clientY - rect.top * (canvas.height / rect.height);
      //console.log("x:"+x+",y:"+y);
      for (let item of gitcalendar.positionplusdata) {
        let lenthx = x - item.x;
        let lenthy = y - item.y;
        //console.log(lenthx,lenthy);
        if (0 < lenthx && lenthx < lineminwitdh) {
          if (0 < lenthy && lenthy < lineminwitdh) {
            //console.log(item.date,item.count)
            document.querySelector('.angle-wrapper').style.display = 'block'
            gitcalendar.span1 = item.date;
            gitcalendar.span2 = item.count;
            gitcalendar.x = event.clientX - 100;
            gitcalendar.y = event.clientY - 60
          }
        }
        //if(0< x - item.x <lineminwitdh&&0< y - item.y <lineminwitdh){
        //console.log(item.count,item.date);
        //}
      }
    }
  }
}
//数据统计算法
function addlastmonth() {
  if (gitcalendar.thisdayindex === 0) {
    thisweekcore(52);
    thisweekcore(51);
    thisweekcore(50);
    thisweekcore(49);
    thisweekcore(48);
    gitcalendar.thisweekdatacore += gitcalendar.firstdate[6].count;
    gitcalendar.amonthago = gitcalendar.firstdate[6].date
  } else {
    thisweekcore(52);
    thisweekcore(51);
    thisweekcore(50);
    thisweekcore(49);
    thisweek2core();
    gitcalendar.amonthago = gitcalendar.first2date[gitcalendar.thisdayindex - 1].date
  }
};

function thisweek2core() {
  for (let i = gitcalendar.thisdayindex - 1; i < gitcalendar.first2date.length; i++) {
    gitcalendar.thisweekdatacore += gitcalendar.first2date[i].count
  }
};

function thisweekcore(index) {
  for (let item of gitcalendar.data[index]) {
    gitcalendar.thisweekdatacore += item.count
  }
};

function addlastweek() {
  for (let item of gitcalendar.lastweek) {
    gitcalendar.weekdatacore += item.count
  }
};

function addbeforeweek() {
  for (let i = gitcalendar.thisdayindex; i < gitcalendar.beforeweek.length; i++) {
    gitcalendar.weekdatacore += gitcalendar.beforeweek[i].count
  }
};

function addweek(data) {
  if (gitcalendar.thisdayindex === 6) {
    gitcalendar.aweekago = gitcalendar.lastweek[0].date;
    addlastweek()
  } else {
    lastweek = data.contributions[51];
    gitcalendar.aweekago = lastweek[gitcalendar.thisdayindex + 1].date;
    addlastweek();
    addbeforeweek()
  }
}

fetch(githubapiurl)
  .then(data => data.json())
  .then(data => {
    gitcalendar.data = data.contributions;
    gitcalendar.total = data.total;
    gitcalendar.first2date = gitcalendar.data[48];
    gitcalendar.firstdate = gitcalendar.data[47];
    gitcalendar.firstweek = data.contributions[0];
    gitcalendar.lastweek = data.contributions[52];
    gitcalendar.beforeweek = data.contributions[51];
    gitcalendar.thisdayindex = gitcalendar.lastweek.length - 1;
    gitcalendar.thisday = gitcalendar.lastweek[gitcalendar.thisdayindex].date;
    gitcalendar.oneyearbeforeday = gitcalendar.firstweek[0].date;
    gitcalendar.monthindex = gitcalendar.thisday.substring(5, 7) * 1;
    gitcalendar.montharrbefore = gitcalendar.month.splice(gitcalendar.monthindex, 12 - gitcalendar.monthindex);
    gitcalendar.monthchange = gitcalendar.montharrbefore.concat(gitcalendar.month);
    addweek(data);
    addlastmonth();
    responsiveChart();
  })
  .catch(function(error) {
    console.log(error);
  });

//手机版更换为svg绘制
if (document.getElementById("gitcalendarcanvasbox").offsetWidth < 500) {
  gitcalendar.simplemode = false
}

//当改变窗口大小时重新绘制canvas
window.onresize = function() {
  if (gitcalendar.simplemode) responsiveChart()
}

//解决滚动滑轮时出现的标签显示
window.onscroll = function() {
  if (document.querySelector('.angle-wrapper')) {
    document.querySelector('.angle-wrapper').style.display = 'none'
  }
};</script></div><script src="/live2dw/lib/L2Dwidget.min.js?094cbace49a39548bed64abff5988b05"></script><script>L2Dwidget.init({"pluginRootPath":"live2dw/","pluginJsPath":"lib/","pluginModelPath":"assets/","tagMode":false,"log":false,"model":{"jsonPath":"/live2dw/assets/hijiki.model.json"},"display":{"position":"right","width":150,"height":300},"mobile":{"show":true},"react":{"opacity":0.7}});</script></body></html>